import { defineStore } from "pinia";
import { store } from "@/store";
import type { toRouteType } from "@/router";

export const useCachedViewStore = defineStore({
  id: "cached-view",
  state: () => ({
    // 缓存页面 keepAlive
    cachedViewList: [] as string[],
    userInfo: {
      ID: "",
      CreatedAt: "",
      UpdatedAt: "",
      DeletedAt: "",
      Name: "",
      PassWord: "",
      Phone: "",
      Email: "",
      Identifier: "",
      ClientIP: "",
      ClientPort: "",
      LoginTime: 0,
      HeartbeatTime: 0,
      LogoutTime: 0,
      IsLogout: false,
      DeviceInfo: ""
    }
  }),

  actions: {
    addCachedView(view: toRouteType) {
      // 不重复添加
      if (this.cachedViewList.includes(view.name as string)) return;
      if (!view?.meta?.noCache) {
        this.cachedViewList.push(view.name as string);
      }
    },
    delCachedView(view: toRouteType) {
      const index = this.cachedViewList.indexOf(view.name as string);
      index > -1 && this.cachedViewList.splice(index, 1);
    },
    delAllCachedViews() {
      this.cachedViewList = [] as string[];
    },
    setUserInfo(info) {
      this.userInfo = info;
    }
  },

  persist: {
    storage: localStorage, // 指定使用 sessionStorage 进行持久化
    paths: ["userInfo"] // 要持久化的状态路径
  }
});

export function useCachedViewStoreHook() {
  return useCachedViewStore(store);
}
